package com.miracle.mvplib.base

import androidx.annotation.CallSuper
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner

/**
 * created by miracle on 2022/2/11
 * Desc:使用方法：1.继承此抽象类
 *              2.实现自己的契约类Contract中Presenter接口
 *              3.对应页面的生命周期 有onCreate() onStart() onResume()...onDestroy()等方法，根据需要自己写业务逻辑
 */
abstract class BasePresenter<T : IView>(view: T) : LifecycleEventObserver {
    protected var mView: T? = null

    init {
        mView = view
        mView?.let {
            attachView(it)
        }
    }

    private fun attachView(view: T) {
        if (view is LifecycleOwner)
            view.lifecycle.addObserver(this)

    }

    private fun detachView() {
        mView = null
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_CREATE -> onCreate()
            Lifecycle.Event.ON_START -> onStart()
            Lifecycle.Event.ON_RESUME -> onResume()
            Lifecycle.Event.ON_PAUSE -> onPause()
            Lifecycle.Event.ON_STOP -> onStop()
            Lifecycle.Event.ON_DESTROY -> onDestroy()
            Lifecycle.Event.ON_ANY -> onAny()
        }
    }

    @CallSuper
    open fun onAny() {
    }

    @CallSuper
    open fun onDestroy() {
    }

    @CallSuper
    open fun onStop() {
        detachView()
    }

    @CallSuper
    open fun onPause() {
    }

    @CallSuper
    open fun onResume() {
    }

    @CallSuper
    open fun onStart() {
    }

    @CallSuper
    open fun onCreate() {
    }
}